<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chat extends Admin_Controller {

	public function __construct()
	{
  		parent::Admin_Controller();
		$this->lang->load('admin_chat');
		$this->lang->load('chat');
		$this->load->library('chat/common_lib');
		$this->load->library('chat/chat_lib');
		$this->load->library('chat/operator_lib');
		$this->load->library('chat/groups_lib');
		$this->load->library('chat/expand_lib');
		$this->load->config('language');
		$this->load->config('chat');
	}
	public function away()
	{
		$operator = $this->operator_lib->check_login();
		$this->chat_lib->notify_operator_alive($operator['operatorid'], 1);
		redirect('admin/chat');
	}
	public function index()
	{
		$this->template->set('layout', 'chat')->load('blank');
	}
	public function iframe()
	{
		$operator = $this->operator_lib->check_login();
		$isonline = empty($operator)? FALSE: $this->operator_lib->is_operator_online($operator['operatorid']);
		$this->template->set('layout', FALSE)->load('chat/chat', array('isonline' => $isonline));
	}
	public function update()
	{
		$since = $this->input->post('since');
		$status = $this->input->post('since');
		$showonline = $this->input->post('showonline');
		$operatorgroups = $this->session->userdata('operatorgroups');
		$groupids = "";
		$this->common_lib->start_xml_output();
		echo '<update>';
		if ($showonline) {
			$this->print_operators();
		}
		$this->print_pending_threads($groupids, $since);
		$operator = $this->operator_lib->check_login();
		echo '</update>';
		$this->chat_lib->notify_operator_alive($operator['operatorid'], $status);
		exit;
	}
	function thread_to_xml($thread)
	{
		$threadstate_to_string = array(
				$this->chat_lib->state_queue => "wait",
				$this->chat_lib->state_waiting => "prio",
				$this->chat_lib->state_chatting => "chat",
				$this->chat_lib->state_closed => "closed",
				$this->chat_lib->state_loading => "wait",
				$this->chat_lib->state_left => "closed"
		);
		
		$threadstate_key = array(
				$this->chat_lib->state_queue => "chat.thread.state_wait",
				$this->chat_lib->state_waiting => "chat.thread.state_wait_for_another_agent",
				$this->chat_lib->state_chatting => "chat.thread.state_chatting_with_agent",
				$this->chat_lib->state_closed => "chat.thread.state_closed",
				$this->chat_lib->state_loading => "chat.thread.state_loading"
		);
		$operator = $this->operator_lib->check_login();
		$state = $threadstate_to_string[$thread['istate']];
		$result = "<thread id=\"" . $thread['threadid'] . "\" stateid=\"$state\"";
		if ($state == "closed")
			return $result . "/>";
	
		$state = lang($threadstate_key[$thread['istate']]);
		$nextagent = $thread['nextagent'] != 0 ? $this->operator_lib->operator_by_id_($thread['nextagent']) : null;
		$threadoperator = $nextagent ? $nextagent['vclocalename'] : ($thread['agentName'] ? $thread['agentName'] : "-");
	
		if ($threadoperator == "-" && $thread['groupname']) {
			$threadoperator = "- " . $thread['groupname'] . " -";
		}
	
		if (!($thread['istate'] == $this->chat_lib->state_chatting && $thread['agentId'] != $operator['operatorid'] && !$this->operator_lib->is_capable($this->operator_lib->can_takeover, $operator))) {
			$result .= " canopen=\"true\"";
		}
		if ($thread['agentId'] != $operator['operatorid'] && $thread['nextagent'] != $operator['operatorid']
				&& $this->operator_lib->is_capable($this->operator_lib->can_viewthreads, $operator)) {
			$result .= " canview=\"true\"";
		}
		$enableban = $this->config->item('enableban', 'chat');
		if ($enableban == "1") {
			$result .= " canban=\"true\"";
		}
	
		$banForThread = $enableban == "1" ? $this->chat_lib->ban_for_addr_($thread['remote']) : false;
		if ($banForThread) {
			$result .= " ban=\"blocked\" banid=\"" . $banForThread['banid'] . "\"";
		}
	
		$result .= " state=\"$state\" typing=\"" . $thread['userTyping'] . "\">";
		$result .= "<name>";
		if ($banForThread) {
			$result .= htmlspecialchars(lang('chat.client.spam.prefix'));
		}
		$result .= htmlspecialchars(htmlspecialchars($thread['userName'])) . "</name>";
		$result .= "<addr>" . htmlspecialchars($thread['remote']) . "</addr>";
		$result .= "<agent>" . htmlspecialchars(htmlspecialchars($threadoperator)) . "</agent>";
		$result .= "<time>" . $thread['unix_timestamp(dtmcreated)'] . "000</time>";
		$result .= "<modified>" . $thread['unix_timestamp(dtmmodified)'] . "000</modified>";
	
		if ($banForThread) {
			$result .= "<reason>" . $banForThread['comment'] . "</reason>";
		}
	
		$userAgent = $this->common_lib->get_useragent_version($thread['userAgent']);
		$result .= "<useragent>" . $userAgent . "</useragent>";
		if ($thread["shownmessageid"] != 0) {
			$this->load->model('chat/message_model', 'message_m');
			$line = $this->message_m->get_message($thread["shownmessageid"]);
			if ($line) {
				$message = preg_replace("/[\r\n\t]+/", " ", $line["tmessage"]);
				$result .= "<message>" . htmlspecialchars(htmlspecialchars($message)) . "</message>";
			}
		}
		$result .= "</thread>";
		return $result;
	}
	
	function print_pending_threads($groupids, $since)
	{
		$revision = $since;
		$output = array();
		$this->load->model('chat/thread_model', 'thread_m');
		$state_closed = $this->chat_lib->state_closed;
		$state_left = $this->chat_lib->state_left;
		$sql = "select threadid, userName, agentName, unix_timestamp(dtmcreated), userTyping, " .
				"unix_timestamp(dtmmodified), lrevision, istate, remote, nextagent, agentId, userid, shownmessageid, userAgent, (select vclocalname from chatgroup where chatgroup.groupid = chatthread.groupid) as groupname " .
				"from chatthread where lrevision > $since " .
				($since <= 0
						? "AND istate <> $state_closed AND istate <> $state_left "
						: "") . " ORDER BY threadid";
		$rows = $this->thread_m->select_rows($sql);
		if(!empty($rows)){
			foreach ($rows as $row) {
				$thread = $this->thread_to_xml($row);
				$output[] = $thread;
				if ($row['lrevision'] > $revision){
					$revision = $row['lrevision'];
				}
			}
		}
	
		echo "<threads revision=\"$revision\" time=\"" . time() . "000\">";
		foreach ($output as $thr) {
			print $thr;
		}
		echo "</threads>";
	}
	
	function print_operators()
	{
		echo "<operators>";
		$operators = $this->operator_lib->operator_get_all();
		
		foreach ($operators as $operator) {
			if (!$this->operator_lib->operator_is_online($operator))
					continue;
			
					$name = htmlspecialchars(htmlspecialchars($operator['vclocalename']));
					$away = $this->operator_lib->operator_is_away($operator) ? " away=\"1\"" : "";
			
			echo "<operator name=\"$name\"$away/>";
		}
		echo "</operators>";
	}
	public function agent($threadid, $token = NULL, $remote_level = "ajaxed", $viewonly = false, $forcetake = false)
	{
		$operator = $this->operator_lib->check_login();
		
		if (empty($token)) {
		
			$remote_level = $this->chat_lib->get_remote_level($_SERVER['HTTP_USER_AGENT']);
			if ($remote_level != "ajaxed") {
				die("old browser is used, please update it");
			}
		
			$thread = $this->chat_lib->thread_by_id_($threadid);
			if (!$thread || !isset($thread['ltoken'])) {
				die("wrong thread");
			}
			if (!$viewonly && $thread['istate'] == $this->chat_lib->state_chatting && $operator['operatorid'] != $thread['agentId']) {
		
				if (!$this->operator_lib->is_capable($this->operator_lib->can_takeover, $operator)) {
					$data = array('msg' => "Cannot take over");
					$this->template->set('layout', FALSE)->load('chat/tips', $data);
					return ;
				}
		
				if ($forcetake == false) {
					$data = array('username' => $thread['userName'], 'agent' => $thread['agentName'], 'link' => site_url("admin/chat/agent/$threadid/0/ajaxed/0/true"));
					$this->template->set('layout', FALSE)->load('chat/confirm', $data);
					return;
				}
			}
		
			if (!$viewonly) {
				$this->chat_lib->take_thread($thread, $operator);
			} else if (!$this->operator_lib->is_capable($this->operator_lib->can_viewthreads, $operator)) {
				$data = array('msg' => "Cannot view threads");
				$this->template->set('layout', FALSE)->load('chat/tips', $data);
				return ;
			}
			$viewonly = $viewonly? 1: 0;
			$token = $thread['ltoken'];
			redirect(site_url("admin/chat/agent/$threadid/$token/$remote_level/$viewonly"));
			exit;
		}
		
		$thread = $this->chat_lib->thread_by_id_($threadid);
		if (!$thread || !isset($thread['ltoken']) || $token != $thread['ltoken']) {
			die("wrong thread");
		}
		
		if ($thread['agentId'] != $operator['operatorid'] && !$this->operator_lib->is_capable($this->operator_lib->can_viewthreads, $operator)) {
			$data = array('msg' => "Cannot view threads");
			$this->template->set('layout', FALSE)->load('chat/tips', $data);
			return ;
		}
		
		$page = array();
		$page['agent'] = true;
		$page['user'] = false;
		if ($viewonly) {
			$page['canpost'] = false;
		}else{
			$page['canpost'] = true;
		}
		$nameisset = lang("chat.default.username") != $thread['userName'];
		$page['displ1'] = $nameisset ? "none" : "inline";
		$page['displ2'] = $nameisset ? "inline" : "none";
		$page['level'] = $remote_level;
		$page['ct_chatThreadId'] = $thread['threadid'];
		$page['ct_token'] = $thread['ltoken'];
		$page['ct_user_name'] = htmlspecialchars($thread['userName']);
		$page['canChangeName'] = $this->config->item('usercanchangename', 'chat') == "1";
		$page['chat_title'] =  $this->config->item('chattitle', 'chat');
		
		$page['ct_company_name'] = $this->config->item('title', 'chat');
		$page['ct_company_chatLogoURL'] = $this->config->item('logo', 'chat');
		$page['webimHost'] = $this->config->item('hosturl', 'chat');
		
		if ($this->config->item('sendmessagekey', 'chat') == 'enter') {
			$page['send_shortcut'] = "Enter";
			$page['ignorectrl'] = 1;
		} else {
			$page['send_shortcut'] = $this->chat_lib->is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
			$page['ignorectrl'] = 0;
		}
		
// 		$params = "thread=" . $thread['threadid'] . "&amp;token=" . $thread['ltoken'];
		
		$page['isOpera95'] = $this->chat_lib->is_agent_opera95();
		$page['neediframesrc'] = $this->chat_lib->needsFramesrc();
		
		$page['frequency'] = $this->config->item('updatefrequency_chat', 'chat');
		
		$this->template->set('layout', FALSE)->load('chat/chat_pannel', $page);
// 		$this->template->set('layout', FALSE)->load('chat', $page);
	}
}